﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;

using iTextSharp.text.pdf;
using iTextSharp.text.xml.xmp;

namespace iPdf
{
    /// <summary>
    /// This is a holder class for PDF metadata
    /// </summary>
    class PdfMetadata
    {
        private Hashtable info = new Hashtable();

        public string Author
        {
            get { return (string)info["Author"]; }
            set { info.Add("Author", value); }
        }
        public string Title
        {
            get { return (string)info["Title"]; }
            set { info.Add("Title", value); }
        }
        public string Subject
        {
            get { return (string)info["Subject"]; }
            set { info.Add("Subject", value); }
        }
        public string Keywords
        {
            get { return (string)info["Keywords"]; }
            set { info.Add("Keywords", value); }
        }
        public string Creator
        {
            get { return (string)info["Creator"]; }
            set { info.Add("Creator", value); }
        }
        public string Producer
        {
            get { return (string)info["Producer"]; }
            set { info.Add("Producer", value); }
        }

        public Hashtable Data
        {
            get
            {
              return this.info;
            }
        }

        public byte[] GetStreamedMetadata()
        {
            MemoryStream os = new MemoryStream();
            XmpWriter xmp = new XmpWriter(os, this.info);
            xmp.Close();
            return os.ToArray();
        }

    }


    class PdfSigner: SinglePdfManipulator<SignOption>
    {

        protected override void OpenStamper()
        {
            //Activate MultiSignatures
            stamper = PdfStamper.CreateSignature(reader, destFileStream, '\0', null, false);
        }

        protected override void Manipulate()
        {
            stamper.MoreInfo = pageOption.Metadata.Data;
            stamper.XmpMetadata = pageOption.Metadata.GetStreamedMetadata();
            PdfSignatureAppearance sap = stamper.SignatureAppearance;

            sap.SetCrypto(pageOption.Certificate.PrivateKey, pageOption.Certificate.GetCertificates(), null, PdfSignatureAppearance.WINCER_SIGNED);
            sap.Reason = pageOption.Reason;
            sap.Contact = pageOption.Contact;
            sap.Location = pageOption.Location;
            sap.CertificationLevel = (int)pageOption.CertifyLevel.Id;
            if (pageOption.VisibleSignature)
                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
        }
    }
}
